package top.raxidin.sys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import top.raxidin.common.VO.Result;
import top.raxidin.common.utils.JwtUtil;
import top.raxidin.sys.domain.DTO.GetUserListPageDTO;
import top.raxidin.sys.entity.Menu;
import top.raxidin.sys.entity.User;
import top.raxidin.sys.entity.UserRole;
import top.raxidin.sys.mapper.UserMapper;
import top.raxidin.sys.mapper.UserRoleMapper;
import top.raxidin.sys.service.IMenuService;
import top.raxidin.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author raxidin
 * @since 2024-11-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private JwtUtil jwtUtil;



    @Autowired
    private IMenuService menuService;


    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Result<?> login(User user) {


        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User loginUser = this.baseMapper.selectOne(wrapper);


        if(loginUser!=null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
//            String key="user:"+UUID.randomUUID();

            //存入redis
            loginUser.setPassword(null);
//            redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);
//            存入jwt
            String token = jwtUtil.createToken(loginUser);


            Map<String,Object> data=new HashMap<>();
            data.put("token",token);
            return Result.success(data);
        }

        return Result.fail(20002,"用户名或密码错误");
    }



    /*@Override
    public Result<?> login(User user) {


        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User loginUser = this.baseMapper.selectOne(wrapper);


        if(loginUser!=null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
            String key="user:"+UUID.randomUUID();

            //存入redis
            loginUser.setPassword(null);
            redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);


            Map<String,Object> data=new HashMap<>();
            data.put("token",key);
            return Result.success(data);
        }

        return Result.fail(20002,"用户名或密码错误");
    }*/



   /* @Override
    public Result<?> login(User user) {


        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername())
                .eq(User::getPassword,user.getPassword());
        User loginUser = this.baseMapper.selectOne(wrapper);


        if(loginUser!=null){
            String key="user:"+UUID.randomUUID();

            //存入redis
            loginUser.setPassword(null);
            redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);


            Map<String,Object> data=new HashMap<>();
            data.put("token",key);
            return Result.success(data);
        }

        return Result.fail(20002,"用户名或密码错误");
    }*/

    /*@Override
    public Result<?> getUserInfo(String token) {
        Object object = redisTemplate.opsForValue().get(token);
        if(object!=null){
            User user=JSON.parseObject(JSON.toJSONString(object),User.class);
            Map<String,Object> data=new HashMap<>();
            data.put("name",user.getUsername());
            data.put("avatar",user.getAvatar());
            List<String> roles=this.baseMapper.getRoleNameByUserId(user.getId());
            data.put("roles",roles);
            return Result.success(data);
        }
        return Result.fail(20004,"没有搜索到");
    }*/


    @Override
    public Result<?> getUserInfo(String token) {
//        Object object = redisTemplate.opsForValue().get(token);
        User loginUser =null;
        try {
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(loginUser!=null){
//            User user=JSON.parseObject(JSON.toJSONString(object),User.class);
            Map<String,Object> data=new HashMap<>();
            data.put("name",loginUser.getUsername());
            data.put("avatar",loginUser.getAvatar());
            List<String> roles=this.baseMapper.getRoleNameByUserId(loginUser.getId());
            data.put("roles",roles);
            List<Menu> menuList = menuService.getMenuListByUserId(loginUser.getId());
            data.put("menuList",menuList);


            return Result.success(data);
        }
        return Result.fail(20004,"没有搜索到");
    }

    @Override
    public Result<?> logout(String token) {
//        redisTemplate.delete(token);
        return Result.success("退出系统");
    }

    @Override
    public Result<?> getUserListPage(GetUserListPageDTO userListPageDTO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(userListPageDTO.getUsername()!=null && userListPageDTO.getUsername()!="",User::getUsername,userListPageDTO.getUsername());
        wrapper.eq(userListPageDTO.getPhone()!=null && userListPageDTO.getPhone()!="",User::getPhone,userListPageDTO.getPhone());
        wrapper.orderByDesc(User::getId);


        Page<User> page = new Page<>(userListPageDTO.getPageNo(),userListPageDTO.getPageSize());
        Page<User> userPage = this.baseMapper.selectPage(page, wrapper);
        Map<String ,Object> data=new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return Result.success(data);
    }

    @Override
    @Transactional
    public Result<?> getUserByUserName(User user) {
        //判断在数据库中是否存在同名的用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());

        User u = this.baseMapper.selectOne(wrapper);
        if(u==null){
            //不存在
            user.setPassword(passwordEncoder.encode(user.getPassword()));
             this.save(user);

             //角色写入
            List<Integer> roleIdList = user.getRoleIdList();
            if(roleIdList!=null){
                for (Integer roleId : roleIdList) {
                    userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
                }
            }

            return Result.success("新增用户成功");
        }
        return Result.fail("用户名已存在");
    }

    @Override
    public User getUserById(Integer id) {
        User user = this.baseMapper.selectById(id);
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleMapper.selectList(wrapper);
        List<Integer> roleIdList = userRoles.stream()
                .map(userRole ->{return userRole.getRoleId();})
                .collect(Collectors.toList());
        user.setRoleIdList(roleIdList);

        return user;
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        //更新用户表
        this.baseMapper.updateById(user);


        //删除原有的角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(wrapper);

        //设置新的角色


        List<Integer> roleIdList = user.getRoleIdList();
        if(roleIdList!=null){
            for (Integer roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public void deleteUserById(Integer id) {
        this.baseMapper.deleteById(id);


        //删除原有的角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        userRoleMapper.delete(wrapper);

    }
}
